package com.uyayo.framework.web.support;

import com.google.common.base.Strings;
import com.google.common.net.HttpHeaders;
import com.uyayo.framework.web.constants.CharacterConstants;
import com.uyayo.framework.web.model.RequestDefaultInfo;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import javax.servlet.http.HttpServletRequest;

/***
 * 请求数据
 *
 * @author: Best m
 * @date: 2019/5/23
 * @since: 1.0
 */
public class RequestDefaultHelper implements RequestBaseHelper {
    private static final String[] PROXY_REMOTE_IP_ADDRESS = {"x-forwarded-for","X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};

    @Override
	public RequestDefaultInfo getRequestInfo(HttpServletRequest request) {

        String curIp = getIpAddr(request);
        String userAgentString = request.getHeader(HttpHeaders.USER_AGENT);
        String protocol = request.getHeader("X-Forwarded-Proto");
        if (Strings.isNullOrEmpty(protocol)){
            protocol = request.getScheme();
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        RequestDefaultInfo requestInfo = new RequestDefaultInfo();
		requestInfo.setDomain(request.getServerName());
		requestInfo.setUrl(request.getRequestURL().toString());
		requestInfo.setBrowser(userAgent.getBrowser().getName());
		requestInfo.setOperatingSystem(operatingSystem.getName());
		requestInfo.setRequestIp(curIp);
		requestInfo.setUserAgent(userAgentString);
		requestInfo.setProtocol(protocol);
        return requestInfo;
    }

	/**
     * 获取用户真实IP
     *
     * @param request request请求
     * @return String IP
     */
    public static String getIpAddr(HttpServletRequest request) {
        for (String headerKey : PROXY_REMOTE_IP_ADDRESS) {
            String header = request.getHeader(headerKey);
            if (!Strings.isNullOrEmpty(header) &&
                    !CharacterConstants.UNKNOWN_STRING.equalsIgnoreCase(header)) {
                String[] strings = header.split(",");
                for (String string : strings) {
                    String value = string.trim();
                    if (!Strings.isNullOrEmpty(value) &&
                            !CharacterConstants.UNKNOWN_STRING.equalsIgnoreCase(value)) {
                        return value;
                    }
                }
            }
        }
        return request.getRemoteAddr().trim();
    }
}
